#include "csmartputty.h"
#include "ui_csmartputty.h"
#include "addconnectdialog.h"
#include "getfiledialog.h"
#include "cputfiledialog.h"
#include <QDebug>
#include <QStandardItemModel>
#include <QProcess>
#include <QDateTime>
#include <QDir>

CLoginCfgMgr* CLoginCfgMgr::m_pSingleton = NULL;

CLoginCfgMgr* CLoginCfgMgr::singleton()
{
    if (m_pSingleton == NULL)
    {
        m_pSingleton = new CLoginCfgMgr();
        m_pSingleton->setCfg(QDir::currentPath()+"/cfg.ini");
        m_pSingleton->init();
    }
    return m_pSingleton;
}

void CLoginCfgMgr::setCfg(QString strCfg)
{
    m_strCfgName = strCfg;
}

int CLoginCfgMgr::init()
{
    return read_plain_txt_cfg(m_strCfgName);
}

int CLoginCfgMgr::read_plain_txt_cfg(QString strCfg)
{
    m_connItemVec.clear();
    QFile file(strCfg);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "open file failed : "<<strCfg;
        return S_COMMON_ERROR;
    }
    int iRet = S_SUCCESS;
    while (!file.atEnd())
    {
        iRet = read_plain_txt_item(file);
        if(S_SUCCESS != iRet)
        {
            qDebug() << "read config item from file "<<strCfg<<" failed";
            break;
        }
    }
    file.close();
    return iRet;
}

int CLoginCfgMgr::read_plain_txt_item(QFile& file)
{
    if(file.atEnd())
    {
        return S_SUCCESS;
    }
    TConnectItem item;
    if (read_plain_txt_line(file,item.m_name) != S_SUCCESS
        ||read_plain_txt_line(file,item.m_ip) != S_SUCCESS
        ||read_plain_txt_line(file,item.m_user) != S_SUCCESS
        ||read_plain_txt_line(file,item.m_passwd) != S_SUCCESS)
    {
        return S_COMMON_ERROR;
    }
    item.m_idx = m_connItemVec.size();
    m_connItemVec.push_back(item);
    return S_SUCCESS;
}

int CLoginCfgMgr::read_plain_txt_line(QFile& file,QString& strVal)
{
    if(file.atEnd())
    {
        qDebug() << "read file ending.";
        return S_COMMON_ERROR;
    }
    strVal = file.readLine().trimmed();
    return S_SUCCESS;
}

int CLoginCfgMgr::addConnectItem(CLoginCfgMgr::TConnectItem& item)
{
    QFile file(m_strCfgName);
    if (!file.open(QIODevice::Append | QIODevice::Text))
    {
        qDebug() << "open file failed : "<<m_strCfgName;
        return S_COMMON_ERROR;
    }
    QByteArray backtrce = "\n";

    file.write(item.m_name.toUtf8()+backtrce);
    file.write(item.m_ip.toUtf8()+backtrce);
    file.write(item.m_user.toUtf8()+backtrce);
    file.write(item.m_passwd.toUtf8()+backtrce);

    file.close();

    return S_SUCCESS;
}

QVector<CLoginCfgMgr::TConnectItem>& CLoginCfgMgr::getConn(QString strKey)
{
    m_matchConnItemVec.clear();
    QVector<CLoginCfgMgr::TConnectItem>::iterator itor = m_connItemVec.begin();
    for (;itor != m_connItemVec.end();itor++)
    {
        TConnectItem& item = *itor;
        if (item.match(strKey))
        {
            m_matchConnItemVec.push_back(item);
        }
    }
    return m_matchConnItemVec;
}

CLoginCfgMgr::TConnectItem& CLoginCfgMgr::getConn(int idx)
{
    QVector<CLoginCfgMgr::TConnectItem>::iterator itor = m_connItemVec.begin();
    for (;itor != m_connItemVec.end();itor++)
    {
        TConnectItem& item = *itor;
        if (item.m_idx == idx)
        {
            return item;
        }
    }
    return m_connItemVec[0];
}
///////////////////////////////////////////////////////////
int CSSHLoginHelper::login(CLoginCfgMgr::TConnectItem& item)
{
    qDebug() << "login into "+ item.m_ip +" "+ item.m_name;

    QProcess* p = new QProcess();
    QString c = "putty.exe "+item.m_ip+" -l "+item.m_user+" -pw "+item.m_passwd;
    p->start(c);

    return S_SUCCESS;
}
///////////////////////////////////////////////////////////
CSmartPutty::CSmartPutty(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CSmartPutty)
{
    ui->setupUi(this);
    init();

    connect(ui->actionAdd_connect
            , SIGNAL(triggered())
            , this
            , SLOT(on_add_connect_clicked()));
    ui->connsView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->connsView
            , SIGNAL(customContextMenuRequested(const QPoint&))
            , this
            , SLOT(show_context_menu(const QPoint&)));
}

CSmartPutty::~CSmartPutty()
{
    delete ui;
}

int CSmartPutty::init()
{
    displayConn(CLoginCfgMgr::singleton()->getConn());
}

int CSmartPutty::displayConn(QVector<CLoginCfgMgr::TConnectItem>& connVec)
{
    ui->connsView->clear();
    QVector<CLoginCfgMgr::TConnectItem>::iterator itor = connVec.begin();
    for (;itor != connVec.end();itor++)
    {
        CLoginCfgMgr::TConnectItem& item = *itor;
        QString displayStr = "["+QString::number(item.m_idx, 10)+"]"+item.m_name + "(" + item.m_user+"@" + item.m_ip + ")";
        ui->connsView->addItem(displayStr);
    }
    return S_SUCCESS;
}

void CSmartPutty::on_filterEdit_textChanged(const QString &arg1)
{
    displayConn(CLoginCfgMgr::singleton()->getConn(arg1));
}

int CSmartPutty::getConnIdx(QString strConn)
{
    int iBegin = strConn.indexOf('[') + 1;
    QString strIdx = strConn.mid(iBegin,1);
    return strIdx.toInt();
}

void CSmartPutty::printLog(QString log)
{
    ui->logEdit->append("[" +
        QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss") +
        "] " +
        log);
}

void CSmartPutty::on_connsView_doubleClicked(const QModelIndex &index)
{
    //QString strIdx =
    QList<QListWidgetItem*> itemlist = ui->connsView->selectedItems();
    for (int i = 0;i < itemlist.size();i++)
    {
        QListWidgetItem* pItem = itemlist[i];
        CLoginCfgMgr::TConnectItem& connItem = CLoginCfgMgr::singleton()->getConn(getConnIdx(pItem->text()));
        CSSHLoginHelper::login(connItem);
        printLog("login "+connItem.m_user+"@"+connItem.m_ip);
    }
}

void CSmartPutty::on_connsView_clicked(const QModelIndex &index)
{
    /*
    ui->selectEdit->clear();
    QList<QListWidgetItem*> itemlist = ui->connsView->selectedItems();
    for (int i = 0;i < itemlist.size();i++)
    {
        QListWidgetItem* pItem = itemlist[i];
        ui->selectEdit->append(pItem->text());
    }
    */
}

void CSmartPutty::on_add_connect_clicked()
{
    //qDebug()<< "add connect in";
    AddConnectDialog dialog;
    dialog.exec();
    displayConn(CLoginCfgMgr::singleton()->getConn());
}

void CSmartPutty::show_context_menu(const QPoint& pos)
{
    //qDebug()<<"show_contextmenu1";
    QMenu *cmenu = new QMenu(ui->connsView);
    QAction *getFileAction = cmenu->addAction("取文件");
    QAction *putFileAction = cmenu->addAction("放文件");

    //getFileAction->connect()

    connect(getFileAction, SIGNAL(triggered(bool)), this, SLOT(show_get_file_menu()));
    connect(putFileAction, SIGNAL(triggered(bool)), this, SLOT(show_put_file_menu()));
    cmenu->exec(QCursor::pos());//在当前鼠标位置显示
    //cmenu->exec(pos)是在viewport显示
}
/*
void CSmartPutty::show_context_menu_signal(const QPoint& pos)
{

}
*/
void CSmartPutty::show_get_file_menu()
{
    QList<QListWidgetItem*> itemlist = ui->connsView->selectedItems();
    if (itemlist.size() == 0)
    {
        return;
    }
    QListWidgetItem* pItem = itemlist[0];
    getfiledialog dialog;
    CLoginCfgMgr::TConnectItem& item = CLoginCfgMgr::singleton()->getConn(getConnIdx(pItem->text()));
    //qDebug() << item.m_ip;
    dialog.setConn(item);
    dialog.exec();
}

void CSmartPutty::show_put_file_menu()
{
    QList<QListWidgetItem*> itemlist = ui->connsView->selectedItems();
    if (itemlist.size() == 0)
    {
        return;
    }
    QListWidgetItem* pItem = itemlist[0];
    CPutFileDialog dialog;
    CLoginCfgMgr::TConnectItem& item = CLoginCfgMgr::singleton()->getConn(getConnIdx(pItem->text()));
    //qDebug() << item.m_ip;
    dialog.setConn(item);
    dialog.exec();
}
